import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, FormInstance, Form, Modal } from 'antd';
import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import { useModel } from 'umi';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { history } from 'umi';

import { isNull, showMsg, MsgType } from '@/utils/utils';
import { 
  getPatientHospitalizationInfo,
  getDischargeStatus
}  from '@/services/order/api';
import '../style.less';

interface MyProps {
  id: string;
  type: string;
  onSubmit: Function;
  goodsRef: Object;
  settRef: Object;
  setInfo: Function;
  orderDetail: Object;
  patient: Object;
  onReset: Function;
}

const { confirm } = Modal;

const Result: React.FC<MyProps> = forwardRef((props, ref) => {
  const { onSubmit, type, onReset, setInfo, patient={} } = props;
  const [loading, setLoading] = useState(false);
  const formRef = useRef<FormInstance>();
  const { initialState } = useModel('@@initialState');

  // 患者信息
  const [patientInfo, setPatientInfo] = useState(patient);
  useEffect(() => {
    // setPatientInfo(orderDetail)
    setPatientInfo(patient)
  }, [patient])

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    clear: () => {
      setPatientInfo({});
      formRef.current?.resetFields();
    }
  }))

  // 患者住院信息
  const fetchPatientHospitalizationInfo = async (data: { visit_no: string }) => {
    const list = await getPatientHospitalizationInfo(data);
    const info = list[0]
    if (!info) {
      showMsg('未找到患者信息', MsgType.INFO);
      setPatientInfo({} as ORDERAPI.PatientInfo);
      setInfo({});
      return;
    }
    checkOrder(info);
  }

  function showConfirm() {
    setPatientInfo({});
    formRef.current?.setFieldsValue({ admission_num: null });
    setInfo({});
    onReset?.();
  }

  // 判断是否出院办结
  const checkOrder = async(info) => {
    const data = await getDischargeStatus({
      patient_id: info.patient_id,
      admission_num: info.visit_no
    });
    
    // if (['W'].includes(data.manager_status)) {
    //   showMsg('存在处理中的出院办结信息', MsgType.INFO);
    // } else if (['F'].includes(data.manager_status)) {
    //   showMsg('患者已办理出院，无法创建订单', MsgType.INFO);
    // } else {
      initPage(info);
    // }
  }

  const initPage = (info) => {
    const result = Object.assign({}, info, { mobile: info.contact_tel_no});
    setPatientInfo(Object.assign({}, { ...result, admission_num: info.visit_no }));
    setInfo(Object.assign({}, { ...result, admission_num: info.visit_no }));
    formRef.current?.setFieldsValue({
      patient_name: info.patient_name
    });
    history.replace(`/order/rent/settlement?admission_num=${info.visit_no}&type=edit`)
    onSubmit(info.visit_no);
  }

  // console.log('ygData', orderObj, loading)
  console.log('type', type)
  return (
    <ProForm 
      className="order-pro-form service-record-rent patient-form"
      style={{ padding: '0px 20px' }}
        submitter={
          {
            searchConfig: {
              submitText: isNull(patientInfo.patient_id) ? '查询' : '更换患者'
            },
            resetButtonProps: {
              style: {
                display: 'none'
              }
            },
          }
          //  : false
      } 
      formRef={formRef}
      onFinish={async (values) => {
        console.log(values);
        if (!isNull(patientInfo.patient_id)) {
          showConfirm();
          return;
        }
        const { admission_num } = values;
        if (!admission_num) {
          showMsg('请输入住院号', MsgType.INFO);
          return;
        }
        if (admission_num.length === 7 || admission_num.length === 8) {
          await fetchPatientHospitalizationInfo({
            visit_no: admission_num
          });
        } else {
          showMsg('住院号输入有误', MsgType.INFO);
        }
      }}
      layout='inline'>
      <ProForm.Group>
        <Form.Item label="病区">
          <span>{initialState?.currentUser?.ward_name}</span>
        </Form.Item>
        {
          isNull(patientInfo.patient_id) ? <ProFormText
            label="住院号"
            name="admission_num"
            placeholder="输入住院号"
            width={200}
            fieldProps={{
              onPressEnter: (e) => {
                e.preventDefault();
                formRef.current?.submit()
              }
            }}
          /> : <Form.Item label="住院号">
            <span>{patientInfo.admission_num}</span>
          </Form.Item>
        }
        {
          patientInfo.patient_id &&
          <>
            <Form.Item label="患者姓名">
              <span>{patientInfo.patient_name}</span>
            </Form.Item>
            <Form.Item label="患者状态">
              <span>{patientInfo.admission_status === 'O' ? '已出院' : '住院中'}</span>
            </Form.Item>
          </>
        }
      </ProForm.Group>
    </ProForm>
  );
});

export default Result;
